﻿using KongMing.Project.Entity.Business;
using KongMing.Project.Entity.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KongMing.Project.Common;
using KongMing.Project.IService.Business;
using KongMing.Project.Entity.Dto;
using KongMing.Project.Entity.View;
using SqlSugar;

namespace KongMing.Project.Service.Business
{
    public class UserService : BaseService, IUserService
    {
        public UserService(IServiceProvider serviceProvider) : base(serviceProvider)
        {
        }
        public async Task<BaseApiResult> UserSave(SysUser user)
        {
            user.CheckNull(msg: "用户信息不可为空！");
            if (string.IsNullOrWhiteSpace(user.UserId))
            {
                user.UserId = Guid.NewGuid().ToString("N");
                user.CreateTime = Configs.NowTime;
                int result = await BusinessDB.Insertable(user).ExecuteCommandAsync();
                return BaseApiResult.SaveResult(result);
            }
            else
            {
                int result = await BusinessDB.Updateable(user).ExecuteCommandAsync();
                return BaseApiResult.SaveResult(result);
            }
        }

        public async Task<User_V> UserDetail(string id)
        {
            id.CheckNull(msg: "参数不可为空！");
            var user = await BusinessDB.Queryable<SysUser>().Select<User_V>().FirstAsync(x => x.Id == id);
            return user;
        }

        public async Task<QueryResult<User_V>> UserList(QueryModel<User_R> query)
        {
            if (query == null)
                throw new BusinessException("参数不可为空！");
            query.PageIndex = Math.Max(1, query.PageIndex);
            query.PageSize = Math.Max(20, query.PageSize);
            var exp = Expressionable.Create<SysUser>().And(x => x.IsDelete == 0);
            var user_Q = query.Model;
            if (user_Q != null)
                exp = exp.AndIF(!string.IsNullOrWhiteSpace(query.Model.Name), x => x.Name.Contains(user_Q.Name))
                    .AndIF(!string.IsNullOrWhiteSpace(user_Q.Account), x => x.Account.Contains(user_Q.Account))
                    .AndIF(user_Q.Sex.HasValue, x => x.Sex == user_Q.Sex)
                    .AndIF(user_Q.Age.HasValue, x => x.Age == user_Q.Age)
                    .AndIF(!string.IsNullOrWhiteSpace(user_Q.Phone), x => x.Phone.Contains(user_Q.Phone));
            var _exp = exp.ToExpression();
            RefAsync<int> count = 0;
            var users = await BusinessDB.Queryable<SysUser>().Where(exp.ToExpression()).Select<User_V>().ToPageListAsync(query.PageIndex, query.PageSize, count);
            var result = new QueryResult<User_V>()
            {
                PageIndex = query.PageIndex,
                PageSize = query.PageSize,
                Data = users,
                DataCount = count.Value
            };
            result.ChangePageCount();
            return result;
        }
    }
}
